<template>
  <div class="container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span v-text="title" />
      </div>
      <el-form
        ref="elForm"
        :model="formData"
        :rules="rules"
        size="medium"
        label-width="100px"
      >
        <el-form-item label="学科 :" prop="subjectID">
          <el-select
            v-model="formData.subjectID"
            placeholder="请选择"
            :style="{ width: '30%' }"
            @change="handlesubjectIDSelect"
          >
            <el-option
              v-for="(item, index) in subjectIDOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录 :" prop="catalogID">
          <el-select
            v-model="formData.catalogID"
            placeholder="请选择"
            :style="{ width: '30%' }"
          >
            <el-option
              v-for="(item, index) in catalogIDOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业 :" prop="enterpriseID">
          <el-select
            v-model="formData.enterpriseID"
            placeholder="请选择"
            :style="{ width: '30%' }"
          >
            <el-option
              v-for="(item, index) in enterpriseIDOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市 :" prop="city">
          <el-select
            v-model="formData.province"
            placeholder="请选择"
            filterable
            :style="{ width: '30%', marginRight: '10px' }"
          >
            <el-option
              v-for="(item, index) in provincesOptions"
              :key="index"
              :label="item.province"
              :value="item"
            ></el-option>
          </el-select>
          <el-select
            v-model="formData.city"
            pplaceholder="请选择"
            filterable
            :style="{ width: '30%' }"
          >
            <el-option
              v-for="(item, index) in areaOptions"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方向 :" prop="direction">
          <el-select
            v-model="formData.direction"
            placeholder="请选择"
            :style="{ width: '30%' }"
          >
            <el-option
              v-for="(item, index) in directionOptions"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型 :" prop="questionType">
          <el-radio-group v-model="formData.questionType" size="medium">
            <el-radio
              v-for="(item, index) in typeOptions"
              :key="index"
              :label="item.value + ''"
              :disabled="item.disabled"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度 :" prop="difficulty">
          <el-radio-group v-model="formData.difficulty" size="medium">
            <el-radio
              v-for="(item, index) in difficultyOptions"
              :key="index"
              :label="item.value + ''"
              :disabled="item.disabled"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干 :" prop="question" class="quill-text">
          <vue-quill
            :form-data="formData.question"
            @update:content="
              val => {
                formData.question = val;
              }
            "
          ></vue-quill>
        </el-form-item>

        <!-- 选择题答案 -->
        <el-form-item label="选项 :" v-if="formData.questionType !== '3'">
          <div v-for="index in selectors" :key="index" class="option-group">
            <div
              :is="optionType"
              ref="optionRef"
              v-model="isAns"
              :label="String.fromCharCode(index + 64) + ' ：'"
            />
            <el-input
              v-model="formData.options[index - 1].title"
              class="option-input"
            />
            <el-upload
              class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              :on-success="
                (res, file) => handleUploadSuccess(res, file, index)
              "
            >
              <img
                v-if="formData.options[index - 1].img"
                :src="formData.options[index - 1].img"
                class="avatar"
              />
              <div v-else class="upload-inner">
                <span class="upload-text">上传图片</span>
              </div>
              <span class="cross-close" @click.stop="handleClickDel(index)">
                <span class="el-icon-circle-close"></span>
              </span>
            </el-upload>
          </div>
          <el-button
            v-if="formData.questionType === '2'"
            type="danger"
            icon="el-icon-plus"
            @click="mlen += 1"
            >增加选项与答案</el-button
          >
        </el-form-item>
        <!-- 选择题答案 -->

        <el-form-item label="解析视频 :">
          <el-input v-model="formData.videoURL" />
        </el-form-item>
        <el-form-item label="答案解析 :" prop="answer" class="quill-text">
          <vue-quill
            :form-data="formData.answer"
            @update:content="
              val => {
                formData.answer = val;
              }
            "
          ></vue-quill>
        </el-form-item>
        <el-form-item
          label="题目备注 :"
          prop="remarks"
          :style="{ width: '35%' }"
        >
          <el-input type="textarea" v-model="formData.remarks" />
        </el-form-item>
        <el-form-item label="试题标签 :" prop="tags">
          <el-select
            v-model="formData.tags"
            placeholder="请选择"
            multiple
            :style="{ width: '30%' }"
          >
            <el-option
              v-for="(item, index) in tagsOptions"
              :key="index"
              :label="item.label"
              :value="item.label"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 提交 -->
        <el-form-item size="large">
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button @click="$refs.elForm.resetFields()">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { simple as subList } from '@/api/hmmm/subjects'
import { list as compList } from '@/api/hmmm/companys'
import { list as catalogIDList } from '@/api/hmmm/directorys'
import { provinces, citys } from '@/api/hmmm/citys'
import { simple as tagList } from '@/api/hmmm/tags'
import { direction, questionType, difficulty } from '@/api/hmmm/constants'
import { transformRes } from '@/utils'
import {
  add as quesAdd,
  update as quesUpdate,
  detail as quesDetail
} from '@/api/hmmm/questions'
import vueQuill from '../components/vue-quill'
export default {
  components: {
    vueQuill
  },
  data () {
    return {
      title: '试题录入',
      singleRadio: '',
      multipleChoice: [],
      formData: {
        id: undefined,
        subjectID: undefined,
        catalogID: undefined,
        enterpriseID: undefined,
        province: undefined,
        city: undefined,
        direction: undefined,
        questionType: '1',
        difficulty: '1',
        question: '',
        options: [],
        answer: '',
        videoURL: '',
        remarks: '',
        tags: []
      },
      rules: {
        subjectID: [
          {
            required: true,
            message: '请选择学科',
            trigger: 'change'
          }
        ],
        catalogID: [
          {
            required: true,
            message: '请选择目录',
            trigger: 'change'
          }
        ],
        enterpriseID: [
          {
            required: true,
            message: '请选择企业',
            trigger: 'change'
          }
        ],
        city: [
          {
            required: true,
            message: '请选择城市',
            trigger: 'submit'
          }
        ],
        direction: [
          {
            required: true,
            message: '请选择方向',
            trigger: 'change'
          }
        ],
        questionType: [
          {
            required: true,
            message: '题型不能为空',
            trigger: 'change'
          }
        ],
        difficulty: [
          {
            required: true,
            message: '难度不能为空',
            trigger: 'change'
          }
        ],
        question: [
          {
            required: true,
            message: '题干不能为空',
            trigger: 'change'
          }
        ],
        answer: [
          {
            required: true,
            message: '答案解析不能为空',
            trigger: 'change'
          }
        ],
        tags: [
          {
            required: true,
            message: '试题标签不能为空',
            trigger: 'change'
          }
        ]
      },
      subjectIDOptions: [],
      catalogIDOptions: [],
      enterpriseIDOptions: [],
      directionOptions: direction,
      typeOptions: questionType,
      difficultyOptions: difficulty,
      tagsOptions: [],
      provincesOptions: provinces(),
      mlen: 4
    }
  },
  async created () {
    this.getMultipleOptions()
    const { data: subs } = await subList()
    this.subjectIDOptions = subs
    const {
      data: { items: comps }
    } = await compList()
    this.enterpriseIDOptions = comps.map(comp => ({
      label: comp.company,
      value: comp.id
    }))
  },
  async beforeMount () {
    const q = this.$route.query
    if (q && q.id) {
      this.formData.id = q.id
      this.title = '试题修改'
      try {
        const { data: res } = await quesDetail({ id: this.formData.id })
        // 将响应数据中题型，难度，试题标签进行处理：：因为数据是数字，而我们组件需要的是名字
        this.formData = { ...transformRes(res) }
        // 根据响应的选项数量生成checkbox的数量
        this.mlen = res.options.length
        // 这里根据当前试题，创建相应select
        await this.handlesubjectIDSelect()
        const len = this.tagsOptions.length
        this.tagsOptions = [
          ...new Set(
            this.tagsOptions.concat(
              []
                .concat(this.formData.tags)
                .map((tag, index) => ({ label: tag, value: len + index + 1 }))
            )
          )
        ]
        if (this.formData.questionType === '1') {
          this.singleRadio =
            this.formData.options.find(option => option.isRight).code + ' ：'
        } else if (this.formData.questionType === '2') {
          this.multipleChoice = this.formData.options
            .filter(option => option.isRight)
            .map(ele => ele.code + ' ：')
        }
      } catch (e) {
        this.$message.error(e)
      }
    }
  },
  watch: {
    mlen () {
      this.getMultipleOptions()
    }
  },
  computed: {
    isAns: {
      get () {
        return this.formData.questionType === '1'
          ? this.singleRadio
          : this.multipleChoice
      },
      set (val) {
        if (this.formData.questionType === '1') {
          this.singleRadio = val
        } else {
          this.multipleChoice = val
        }
      }
    },
    optionType () {
      return this.formData.questionType === '1' ? 'el-radio' : 'el-checkbox'
    },
    areaOptions () {
      return citys(this.formData.province)
    },
    selectors () {
      return this.formData.questionType === '1' ? 4 : this.mlen
    }
  },
  methods: {
    async handlesubjectIDSelect () {
      const subId = {
        subjectID: this.formData.subjectID
      }
      const {
        data: { items: catalogIDs }
      } = await catalogIDList(subId)
      this.catalogIDOptions = catalogIDs.map(catalogID => ({
        label: catalogID.directoryName,
        value: catalogID.id
      }))
      const { data: tags } = await tagList(subId)
      this.tagsOptions = tags
    },
    handleUploadSuccess (res, file, index) {
      this.formData.options[index - 1].img = URL.createObjectURL(file.raw)
    },
    handleClickDel (index) {
      this.formData.options[index - 1].img = ''
    },
    handleSubmit () {
      this.$refs.elForm.validate(async validated => {
        if (validated) {
          try {
            if (this.formData.questionType === '1') {
              this.$refs.optionRef.forEach((ele, index) => {
                this.formData.options[index].code = /[A-Z]/.exec(ele.label)[0]
                if (ele.label.startsWith(this.singleRadio)) {
                  this.formData.options[index].isRight = true
                }
              })
            } else {
              this.$refs.optionRef.forEach((ele, index) => {
                const temp = /[A-Z]/.exec(ele.label)[0]
                this.formData.options[index].code = temp
                if (this.multipleChoice.some(choice => choice === ele.label)) {
                  this.formData.options[index].isRight = true
                }
              })
            }
            this.formData.tags = this.formData.tags.join()
            const reMove = {
              0: () => {
                this.$router.go(-1)
              },
              1: () => {
                this.$router.push({
                  name: 'questions-list'
                })
              }
            }
            let isAdd = 0

            if (this.formData.id) {
              await quesUpdate(this.formData)
            } else {
              await quesAdd(this.formData)
              isAdd = 1
            }

            this.formData.tags = this.formData.tags.split(',')
            this.$message.success(`${this.title.slice(2)}成功`)
            reMove[isAdd]()
          } catch (e) {
            this.$message(e)
          }
        }
      })
    },
    getMultipleOptions () {
      const len = this.formData.options.length
      if (this.mlen > len) {
        for (let i = 0; i < this.mlen - len; i++) {
          this.formData.options.push({
            code: '',
            id: 0,
            img: '',
            isRight: false,
            questionID: 0,
            title: ''
          })
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-button {
  margin-top: 30px;
  font-size: 12px;
}
::v-deep .quill-text .el-form-item__content {
  height: 200px;
}
.option-group {
  display: flex;
  align-items: center;
  margin: 30px 0;
  .el-radio {
    margin-right: 0;
  }
  .option-input {
    width: 18%;
  }
}
::v-deep .avatar-uploader {
  width: 150px;
  height: 80px;
  margin-left: 20px;
  .el-upload {
    width: 100%;
    height: 100%;
    cursor: pointer;
    position: relative;
    .upload-inner {
      height: 100%;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      &:hover {
        border-color: #409eff;
      }
    }
    .upload-text {
      font-size: 12px;
      line-height: 80px;
    }
    .cross-close {
      position: absolute;
      top: 0;
      right: 0;
      transform: translate(50%, -50%);
    }
  }
}
::v-deep .avatar {
  width: 100%;
  height: 100%;
  display: block;
}
</style>
